package iss.java;
import com.sun.xml.internal.ws.api.pipe.ThrowableContainerPropertySet;
import iss.java.list.Mylist;
import iss.java.list.Node;
import javax.swing.plaf.synth.SynthRadioButtonMenuItemUI;
import java.util.*;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
 * Created by wenke on 2016/9/16.
 */
public class Main_A {
    public static void main(String[] args) {
        // TODO: Implement a multithreaded test case against requirement A.
        MyList list = new MyList();
        list.insert(list.getHead(), 5);
        list.insert(list.getHead(), 4);
        list.insert(list.getHead(), 3);
        list.insert(list.getHead(), 2);
        list.insert(list.getHead(), 1);

        Node node=list.getHead().getNext();

        Thread w1=new Thread(new WriteData(node,1));
        Thread w2=new Thread(new WriteData(node,2));
        Thread w3=new Thread(new WriteData(node,-1));
        Thread w4=new Thread(new WriteData(node,-2));

        Thread r1=new Thread(new ReadData(node));
        Thread r2=new Thread(new ReadData(node));

        r1.start();
        w1.start();
        w2.start();
        w3.start();
        w4.start();
        r2.start();

        Thread.sleep(5000);
        System.out.println(node.getData());

    }
}
class WriteData implements Runnable{
    private Node node;
    private int number;
    private ReadWriteLock readwritelock=new ReentrantReadWriteLock();
    public WriteData(Node node,int number){
        this.node=node;
        this.number=number;
    }
    public void run(){
        readwritelock.writelock().lock();
        try{
            for(int i = 0;i < 100;i++){
                node.setData(node.getData()+number);
            }
            System.out.println(number*100+"done"+"now"+node.getData());
        }
        finally{
            readwritelock.writelock().unlock();
        }
    }
}
class ReadData implements Runnable{
    private Node node;
    private ReadWriteLock readwritelock=new ReentrantReadWriteLock();
    public ReadData(Node node){
        this.node=node;
    }
    public void run(){
        readwritelock.readlock().lock();
        try{
            System.out.println(node.getData());
        }
        finally{
            readwritelock.readlock().unlock();
        }
    }
}
